﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Storage.Pickers;
using Windows.Storage;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Popups;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media.Imaging;
using System.Threading;
using System.Threading.Tasks;



// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace StudyTime_1
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class cardBuilder : StudyTime_1.Common.LayoutAwarePage
    {
        public List<studyCard> studyList = new List<studyCard>();
        private bool saveLocation = false;
        private string filePath;
        private string fileName = "goo.xml";
        private string deckPath;
        private string deckName = "goo.xml";
        private StorageFile storage;
        private StorageFile storage2;
        private StorageFile storage3;
        private StorageFile tempStorage;
        private Stream outStream;
        private Stream outStream2;
        private DataContractSerializer xml;
        private DataContractSerializer xml2;
        private DataContractSerializer xml3;
        private bool shownMessage = false;
        private bool listMade = false;
        
        private byte[] img;


        

        public cardBuilder()
        {
            this.InitializeComponent();

            App.studyCardList.Clear();
           // App.stFile = null;

            if (App.fromManager == true)
            {
                loadFromManager();
            }

            //App.stFile = null;
        }

        async public void loadFromManager()
        {
            if (App.stFile != null)
            {
                await classes.serializer.load(true);

                cardCount.Text = App.studyCardList.Count.ToString();
            }
        }



        async private void append(List<studyCard> convert)
        {
            try
            {
                var file = await storage.OpenAsync(FileAccessMode.ReadWrite);
                outStream2 = file.AsStreamForWrite();


                xml2 = new DataContractSerializer(typeof(List<studyCard>));

                xml2.WriteObject(outStream2, convert);

                await outStream2.FlushAsync();
                file.Dispose();

                errorBox.Text = "Saved Successfully!";
            }
            catch (IOException)
            {
                errorBox.Text = "Cannot write to the file";
            }

        }


        async public void selection()
        {

            FileSavePicker savePicker = new FileSavePicker();
            savePicker.SuggestedStartLocation = PickerLocationId.Downloads;
            savePicker.SuggestedFileName = "studycard";
            savePicker.DefaultFileExtension = ".studycardxml";   
            savePicker.FileTypeChoices.Add("STUDYCARD", new List<string>() { ".studycardxml" });

            if (storage != null)
                {
                    tempStorage = storage;
                }
           
            storage = await savePicker.PickSaveFileAsync();
            

            if (null != storage)
            {
                // Application now has read/write access to the picked file
                filePath = storage.Path;
                fileName = storage.Name;
                saveLocation = true;
                SerializeXML(studyList);

            }
            else
            {
                storage = tempStorage;
                errorBox.Text = "File was not returned";
            }
        }

        async private void SerializeXML(List<studyCard> convert)
        {
            if (listMade == true)
            {
                storage = storage2;
            }

            try
            {
                
                

                var file = await storage.OpenAsync(FileAccessMode.ReadWrite);
                outStream = file.AsStreamForWrite();



                xml = new DataContractSerializer(typeof(List<studyCard>));


                xml.WriteObject(outStream, convert);

                await outStream.FlushAsync();
                file.Dispose();

                errorBox.Text = "Saved Successfully!";
            }
            catch (IOException)
            {
                errorBox.Text = "Cannot write to the file";
            }

        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        async private void addCard_Click(object sender, RoutedEventArgs e)
        {

            if (App.stFile == null)
            {

                await openHelper.savePicker(true);
                //await Task.Run(() => { });
                classes.studyCardAct.addCard(question.Text, answer.Text, img);
            }
            else
            {
                classes.studyCardAct.addCard(question.Text, answer.Text, img);
            }

           


            //*** testing Serializer ***//

            BitmapImage tmpimg = new BitmapImage();
            //studyCard card = new studyCard();
            //card.question = question.Text.ToString();
            //card.answer = answer.Text.ToString();
            //card.picture = img;

            //studyList.Add(card);

            //errorBox.Text = App.studyCardList.Count.ToString() + " " + "Items Added";
            cardCount.Text = App.studyCardList.Count.ToString();
            answer.Text = "";
            question.Text = "";
            img = null;



          

            //if (saveLocation == true || listMade == true)
            //{
            //    SerializeXML(studyList);
            //   // append(studyList);
            //}
            //else
            //{
            //    saveAll.IsEnabled = true;
            //}



            insertPreview.Source = tmpimg;
        }
        /*** NEED TO CHANGE TO OPEN PREVIOUS **/
        private async void saveAll_Click(object sender, RoutedEventArgs e)
        {
            if (shownMessage == false)
            {
                var mDialog = new MessageDialog("You only need to export once. After first export each added item will be appended to the saved file.");
                await mDialog.ShowAsync();
                shownMessage = true;
            }
            else
            {
            }
            selection();
        }

        private void pageRoot_Loaded(object sender, RoutedEventArgs e)
        {
            saveAll.IsEnabled = false;

            Storyboard sb = this.FindName("cardBuilderStory") as Storyboard;
            if (sb != null)
            {
                sb.Begin();
            }
        }

        async private void addImage_Click(object sender, RoutedEventArgs e)
        {

            //openHelper.imgPicker();

            //insertPreview.Source = openHelper.getImage();


            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.List;
            openPicker.SuggestedStartLocation = PickerLocationId.Downloads;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");
            openPicker.FileTypeFilter.Add(".bmp");
            storage3 = await openPicker.PickSingleFileAsync();

            if (null != storage3)
            {

                var file = await storage3.OpenAsync(FileAccessMode.Read);

                Stream inStream = file.AsStreamForRead();

                BitmapImage tmpImg = new BitmapImage();

                using (MemoryStream br = new MemoryStream())
                {
                    inStream.CopyTo(br);
                    img = br.ToArray();

                    //br.Dispose();
                }


                await inStream.FlushAsync();
                file.Dispose();


                var stream = new InMemoryRandomAccessStream();

                using (var writer = new DataWriter(stream))
                {

                    writer.WriteBytes(img);
                    await writer.StoreAsync();
                    writer.DetachStream();


                }
                stream.Seek(0);
                tmpImg.SetSource(stream);

                insertPreview.Source = tmpImg;

                await stream.FlushAsync();


                errorBox.Text = "Image Loaded.";

            }
            else
            {
                errorBox.Text = "File was not returned";
            }

        }

       async private void loadDeck_Click(object sender, RoutedEventArgs e)
        {
            await openHelper.openPicker(false);

            //studyList = openHelper.getStudyCardList();

            //listMade = true;


           // openSelection();
        }
        async private void loadData(List<studyCard> card)
        {

            //convLength = 0;
            //currPage = 0;
            studyList.Clear();
           
            {

                StorageFolder storageFolder = KnownFolders.VideosLibrary;


                {
                    try
                    {


                       xml3 = new DataContractSerializer(typeof(List<studyCard>));

                        var file = await storage2.OpenAsync(FileAccessMode.Read);
                        Stream inStream = file.AsStreamForRead();

                        card = xml3.ReadObject(inStream) as List<studyCard>;

                        foreach (studyCard studyCards in card)
                        {
                            studyList.Add(studyCards);

                        }


                        if (App.stcLoadMSg == true)
                        {
                            var mDialog = new MessageDialog("Since you opened a deck, adding a card will append to the opened deck, there is no need to save again. But the button remains for your comfort.");
                            await mDialog.ShowAsync();
                            shownMessage = true;
                            listMade = true;
                            saveAll.IsEnabled = true;
                           
                            await inStream.FlushAsync(); 
                            file.Dispose();

                        }
                       
                    }
                    catch (IOException)
                    {

                    }
                    catch (SerializationException)
                    {
                        errorBox.Text = "Please select a file that was created with the StudyCards app.";
                    }
                }
            }
        }

        public async void openSelection()
        {
            {
                {

                    FileOpenPicker openPicker = new FileOpenPicker();
                    openPicker.ViewMode = PickerViewMode.List;
                    openPicker.SuggestedStartLocation = PickerLocationId.Downloads;
                    openPicker.FileTypeFilter.Add(".studycardxml");
                    storage2 = await openPicker.PickSingleFileAsync();

                    if (null != storage2)
                    {
                        // Application now has read/write access to the picked file
                        deckName = storage2.Name;
                        deckPath = storage2.Path;
                        loadData(studyList);
                        //questions.Text = fileName + " Click Load if this is the correct File";
                        errorBox.Text = "";

                    }
                    else
                    {
                        errorBox.Text = "File was not returned";
                    }
                }


            }


        }
         private void rmvAd_Click(object sender, RoutedEventArgs e)
        {

            removeAds.setNofication();

            //MessageDialog startDialog = new MessageDialog("If you do not want to see ads again please select Go To Store, otherwise press cancel", "Remove Ads?");
            //UICommand store = new UICommand("Go To Store", onStore);
            //UICommand cancel = new UICommand("Cancel");

            //startDialog.Commands.Add(store);
            //startDialog.Commands.Add(cancel);

            //await startDialog.ShowAsync();
        }

        //async public void onStore(object command)
        //{
        //    Uri pageUri = new Uri("http://apps.microsoft.com/webpdp/app/study-time/ee4a5766-52ff-471d-b743-3ecd3157eee7");
        //    await Windows.System.Launcher.LaunchUriAsync(pageUri);

        //}

    

    }
}
